package com.atguigu.servlet;

import sun.plugin.javascript.navig.Array;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Map;
import java.util.Set;

@WebServlet("/servlet5")
public class Servlet5 extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1.获取请求对象

        //根据参数名获取单个参数值
        String name = req.getParameter("username");
        if (name != null) {
            System.out.println("name is " + name);
            resp.getWriter().write("hello " + name);
        } else {
            resp.getWriter().write("hello guest");
        }
        String password = req.getParameter("userpwd");
        if (password != null){
            System.out.println("password is " + password);
            resp.getWriter().write("password is " + password);
        }else {
            resp.getWriter().write("password is null");
        }
        String[] hobbies = req.getParameterValues("hobby");
        if (hobbies != null){
            System.out.println("hobby is "+hobbies);
            for (String hobby : hobbies) {
                resp.getWriter().write(hobby + " ");
            }
        }else {
            resp.getWriter().write("hobby is null");
        }

        //获取所有的参数名
        Enumeration<String> names = req.getParameterNames();
        while (names.hasMoreElements()){
            String pname = names.nextElement();
            String[] parameterValues = req.getParameterValues(pname);
            if (parameterValues.length>1){
                System.out.println("parameter name is " + pname);
                System.out.println("parameter value is " + parameterValues[0]);
            }
        }

        //返回所有参数的map集合，     key     value
        Map<String, String[]> parameterMap = req.getParameterMap();
        Set<Map.Entry<String, String[]>> entries = parameterMap.entrySet();
        for (Map.Entry<String, String[]> entry : entries){
            String key = entry.getKey();
            String[] value = entry.getValue();
            if (value.length>1){
                System.out.println(key+"="+ Arrays.toString(value));
            }else {
                System.out.println(key+"="+value[0]);
            }
        }

        //读取json类型
//        BufferedReader reader = req.getReader();
        //读取二进制数据字节的输入流
//        ServletInputStream inputStream = req.getInputStream();

    }
}
